/// <reference path="tfcore.js"/>
// #pragma NoCompStart
/*
edNLog.js

	edNLog -- the logger itself, with debug(), info(), warning(), error(), and text() methods
	debug -- a convenience method placed in the root to save a few keystrokes for debug method.
	
Example Use:
edNLog.info("Information here!");	
debug("Here's some debug info"); // this is shorthand

*/
// #pragma NoCompEnd

var edNLog = new function() {
    bPersistState = true;
    // Namespacing
    var sNamespace = "ed_log";
    var sInstance = "edNLog";
    var sDOMInstance = sNamespace + "_" + sInstance;
    var Config_Enabled = true;
    if (Config_Enabled == false && location.href.match(/edNlog/)) { Config_Enabled = true; }
    var bLoggerConfigured = false;
    var nNumMsgsLogged = 0;

    // Public Methods

    function debug(msg, stsk) { logMsg("DEBUG", msg, stsk); }
    function info(msg, stsk) { logMsg("INFO", msg, stsk); }
    function warning(msg, stsk) { logMsg("WARN", msg, stsk); }
    function error(msg, stsk) { logMsg("ERROR", msg, stsk); }

    // This method toggles the on-screen display div on or off as needed
    function toggleDisplay() {
        var oBody = _gE(sDOMInstance + '_body');
        if (oBody.style.display == 'none') {
            oBody.style.display = 'block';
        } else {
            oBody.style.display = 'none';
        }

        if (bPersistState) {
            tf.U.setCookie(sInstance + "_visibility", oBody.style.display);
        }

    }

    // this function clears the on-screen display
    function clearLog() {
        _gE(sDOMInstance + '_logDisplay').innerHTML = '';
        nNumMsgsLogged = 0;
        _gE(sDOMInstance + '_handle').innerHTML = nNumMsgsLogged + ": Msgs";
    }

    function enable() {
        if (!bLoggerConfigured) {
            initializeDisplay();
        }
    }

    //	Public method to set any amount of text into the text area in the footer
    function text(sText) { _gE(sDOMInstance + "_textArea").value = sText; }
    //	Public method to try to get the innerHTML of the element identified in the text input box, and place it into the clipboard from view.


    this.debug = debug;
    this.info = info;
    this.warning = warning;
    this.error = error;
    this.toggleDisplay = toggleDisplay;
    this.clearLog = clearLog;
    this.text = text;
    this.enable = enable;

    /*------------------------------------------------------------------------------------
    Private Methods
    ------------------------------------------------------------------------------------*/

    //This function logs a message. All the level-specific methods (logger.debug, etc.) turn around and call this methods
    function logMsg(level, msg, stsk) {
        if (Config_Enabled) {
            // increase the count in the handle
            nNumMsgsLogged += 1;
            _gE(sDOMInstance + '_handle').innerHTML = nNumMsgsLogged + ": Msgs";
            // Append the log to a display div so it can be seen right away
            var oDisplay = _gE(sDOMInstance + '_logDisplay');
            if (oDisplay.childNodes.length == 0) {
                oDisplay.appendChild(createDisplayRow(level, msg, stsk));
            } else {
                oDisplay.insertBefore(createDisplayRow(level, msg, stsk), oDisplay.childNodes[0]);
            }
        } // end of is config enabled
    }

    // this private method creates the row to add the the display div. It generates what actually gets shown 
    // in the appropriate div each time there's a logged event
    function createDisplayRow(sLevel, sMsg, sTsk) {

        var oRes = document.createElement("div");
        oRes.className = "nlRow";
        if (nNumMsgsLogged / 2 != Math.floor(nNumMsgsLogged / 2)) {
            oRes.style.backgroundColor = "#F6F6F6";
        }

        (sTsk != undefined) ? sTsk = " - " + sTsk : sTsk = "";

        var oSev = document.createElement("div");
        oSev.className = "Sev " + sLevel;

        oSev.appendChild(document.createTextNode(sLevel + sTsk));
        oRes.appendChild(oSev);
        var oTime = document.createElement("span");
        oTime.style.paddingLeft = "3px";
        oTime.style.paddingRight = "8px";
        oTime.appendChild(document.createTextNode(getCurrentTimeFormatted()));
        oRes.appendChild(oTime);
        oRes.appendChild(document.createTextNode(sMsg));

        var oClear = document.createElement("div");
        oClear.style.clear = "both";
        oRes.appendChild(oClear);

        return oRes;
    }

    // this private method returns the current date formated properly with a nice AM/PM
    function getCurrentTimeFormatted() {
        var now = new Date();
        var hours = now.getHours();
        var minutes = now.getMinutes();
        var seconds = now.getSeconds();
        var timeValue = "" + ((hours > 12) ? hours - 12 : hours);
        if (timeValue == "0") timeValue = 12;
        timeValue += ((minutes < 10) ? ":0" : ":") + minutes;
        timeValue += ((seconds < 10) ? ":0" : ":") + seconds;
        timeValue += (hours >= 12) ? " PM" : " AM";

        return timeValue;
    }

    if (Config_Enabled) {
        initializeDisplay();
    }

    // Initialization code. It's wrapped in a try-catch block because if something here fails, there is no other notification

    function initializeDisplay() {
        if (!bLoggerConfigured) {
            // Create the display div if necessary. This writes directly to the document to create the UI for the logger.
            // Note also that there are onclick events here, which call back to the public methods of the class.
            try {
            // default positions if other positions are not available
            var nTop = 2;
            var nRight = 320;
            var sDisplay = "none";

            if (bPersistState) {
                try {
                    var sPersistString = tf.U.getCookie(sInstance + "_position");
                    if (sPersistString != null) {
                        var aTemp = sPersistString.split("|");
                        if (!isNaN(parseInt(aTemp[0]))) {
                            nLeft = aTemp[0];
                        }
                        if (!isNaN(parseInt(aTemp[1]))) {
                            nTop = aTemp[1];
                        }
                    }

                    if (tf.U.getCookie(sInstance + "_visibility") == "block") {
                        sDisplay = "block";
                    }
                } catch (e) {
                    // nullop, just leave the arguments as the default
                }
            } // end if bPersistState

            var sIdToInspect = tf.U.getCookie(sInstance + "_idToInspect");
            sIdToInspect = sIdToInspect == null ? "" : sIdToInspect;
            var sB = [];
            sB.push('<div id="');
            sB.push(sDOMInstance);
            sB.push('_container" class="nlCont" style="top:');
            sB.push(nTop);
            sB.push('px; right:');
            sB.push(nRight);
            sB.push('px;"  onmouseover="if(really_over(this)){');
            sB.push(sInstance);
            sB.push('.toggleDisplay();}" onmouseout="if(really_out(this)){');
            sB.push(sInstance);
            sB.push('.toggleDisplay();}">');
            sB.push('<div id="');
            sB.push(sDOMInstance);
            sB.push('_handle" class="nlHandle" >0: Msgs</div>');
            sB.push('<div id="');
            sB.push(sDOMInstance);
            sB.push('_body" class="nlBody" style="display:');
            sB.push(sDisplay);
            sB.push('"><div id="');
            sB.push(sDOMInstance);
            sB.push('_header" class="nlHeader"><span id="');
            sB.push(sDOMInstance);
            sB.push('_clear" class="nlClear" onclick="');
            sB.push(sInstance);
            sB.push('.clearLog()">clear</span></div><div id="');
            sB.push(sDOMInstance);
            sB.push('_logDisplay" class="nlLogDisp"></div><div id="');
            sB.push(sDOMInstance);
            sB.push('_footer" class="nlFooter">get html:<input id="');
            sB.push(sDOMInstance);
            sB.push('_idToInspect" style="font-size:9px; height:18px;" value="');
            sB.push(sIdToInspect);
            sB.push('" size=42/> <span id="');
            sB.push(sDOMInstance);
            sB.push('_go" style="color: blue;" onclick="');
            sB.push(sInstance);
            sB.push('.getHTML()">go</span><textarea id="');
            sB.push(sDOMInstance);
            sB.push('_textArea" style="width:95%; height: 40px; font-size:9px;"></textarea></div></div></div></div>');

            document.write(sB.join(''));
            _gE(sDOMInstance + "_clear").style.cursor = "pointer";
            _gE(sDOMInstance + "_go").style.cursor = "pointer";


            savePos = function(o, pX, pY, ev) {
                if (o.id == sDOMInstance + "_container") {
                    tf.U.setCookie(sInstance + "_position", +pX + "|" + pY);
                }
            };

            edEnableDrag(sDOMInstance + '_container', null, null, this.savePos);

            bLoggerConfigured = true;
            } catch (e) {
                alert("Code-level error initializing edNLog: " + e.description);
            }
        } // end of initializeDisplay
    }
};

debug=edNLog.debug;
